package com.lv.fast.shiro;

import cn.hutool.core.collection.CollectionUtil;
import com.lv.fast.VO.SysUserVO;
import com.lv.fast.enums.RestResultEnum;
import com.lv.fast.util.Assert;
import com.lv.fast.util.SysUserUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 后台管理Realm
 * @author lv
 * @version 1.0.0
 */
@Component
@Slf4j
@AllArgsConstructor
public class SysRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof BearerToken;
    }


    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        Assert.assertNotNull(primaryPrincipal, RestResultEnum.TOKEN_INVALID);
        SysUserVO user = (SysUserVO) primaryPrincipal;
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        HashSet<String> perms = user.getMenus().stream()
                .map(sysMenuDTO -> sysMenuDTO.getPerms())
                .filter(permList -> CollectionUtil.isNotEmpty(permList))
                .collect(HashSet::new, HashSet::addAll, HashSet::addAll);
        info.setStringPermissions(perms);
        Set<String> roles = user.getRoles().stream().map(sysRoleDTO -> sysRoleDTO.getName()).collect(Collectors.toSet());
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        BearerToken bearerToken = (BearerToken) token;
        SysUserVO user = SysUserUtil.getUserInfoByToken(bearerToken.getToken());
        Assert.assertNotNull(user, RestResultEnum.TOKEN_INVALID);
        return new SimpleAuthenticationInfo(user, bearerToken.getToken(), getName());
    }
}
